package tcp.client;

import exception.CustomException;
import parser.Parser;
import parser.ReadState;
import tcp.utils.StreamUtils;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;

public class JodisClient {
    public static void main(String[] args) {
        String host = "127.0.0.1";
        Integer port = 30000 ;
        Logger logger = Logger.getLogger("JodisClient");
        try {
            // 与服务端建立连接
            Socket socket = new Socket(host, port);

            // 建立输入输出流
            // String msg = "*7\\r\\n$4\\r\\nZADD\\r\\n$6\\r\\nmyzset\\r\\n$2\\r\\nnx\\r\\n$1\\r\\n2\\r\\n$3\\r\\ntwo\\r\\n$1\\r\\n3\\r\\n$5\\r\\nthree\\r\\n";
            String msg2 = "*1\\r\\n$7\\r\\ncommand\\r\\n";
            String msg3 = "*1\\r\\n$7\\r\\nCOMMAND\\r\\n";
            byte[] bs = msg2.getBytes(StandardCharsets.US_ASCII);
            socket.getOutputStream().write(bs);
            socket.getOutputStream().flush();

            Thread readServerThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
                    while (true) {
                        try {
                            ReadState state = ReadState.getDefaultInstance();
                            byte[] bs = StreamUtils.readStream(byteOutputStream, socket.getInputStream(), StreamUtils.readWait(), state);
                            Parser.parse(bs, state);
                            if (state.msgType == Parser.ARRAY) {
                                for (String s : state.resultArr) {
                                    logger.info(s);
                                }
                            } else {
                                logger.info(state.resultStr);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (CustomException ignored) {}
                    }
                }
            });
            readServerThread.start();
            readServerThread.join();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}
